int px, py;
int vx, vy;
int x = 0;

boolean paused = true;
boolean done = true;
int[][] stones; 

void setup() {
  noCursor();
  size(300,300);
  smooth();
  px = width/2;
  py = height/2;
  
  vx = int(random( -8, 8 ));
  vy = -2;
  
  stones = new int[7][4];
  for( int x = 0; x < 7; x++) {
    for( int y = 0; y < 4; y++ ) {
      stones[x][y] = y + 1;
    }
  }
}

void draw() {
  background(50);
  stroke(255);
  strokeWeight(3);
  
  // update postion of the ball 
  if (!paused) update();
 
  // draw all stones that are not removed yet
  // check if all are gone
  done = true;
  for( int x = 0; x < 7; x++) {
    for( int y = 0; y < 4; y++ ) {
      if ( stones[x][y] > 0 ) {
        done = false;
        fill( 128 + 10 * stones[x][y] );
        rect( 10 + x * 40, 10 + y * 20, 40, 20 ); 
      }
    }
  }
  
  // no stone remaining - display yippie message
  if ( done ) {
    paused = true;
    fill(255);
    textSize( 48 );
    text( "JIPPIE!", 50, 200 );
  }
  
  // display text if paused
  if ( paused ) {
    textSize( 16 );
    fill(128);
    text( "press mousebutton to continue", 10, 250 );
  }
  
  fill(128);
  // draw ball
  ellipse(px,py,20,20);
  
  // draw paddle
  rect(mouseX - 35, 270, 70, 20 );
}


void update() {
  // check if ball dropped out of the lower border
  if ( py + vy > height - 10 ) {
    px = width/2;
    py = height/2;
    vx = int(random( -8, 8 ));
    vy = -2;
    paused = true;
  }


  // check if the ball hits a block
  for( int x = 0; x < 7; x++) {
    for( int y = 0; y < 4; y++ ) {
      if ( stones[x][y] > 0 ) {
        if ( px + vx + 10 > 10 + x * 40 && px + vx - 10 < 10 + x * 40 + 40 &&
             py + vy + 10 > 10 + y * 20 && py + vy - 10 < 10 + y * 20 + 20 ) {
          stones[x][y] = 0;
          
          // change the velocity in y direction if the block has been hit 
          // on the bottom or on the top 
          if ( px + 10 > 10 + x * 40 && px - 10 < 10 + x * 40 + 40 ) vy = -vy;
          // change the velocity in the x direction if the block has been hit on the side
          if ( py + 10 > 10 + y * 20 && py - 10 < 10 + y * 20 + 20 ) vx = -vx; 
        }
      }
    }
  }
  
  // change the direction if the ball hits a wall
  if (px + vx  < 10 || px + vx > width - 10) {
    vx = -vx;
  }

  if (py + vy  < 10 || py + vy > height - 10) {
    vy = -vy;
  }
  
  // check if the paddle was hit
  if ( py + vy >= 266  && px >= mouseX - 35 && px <= mouseX +35 ) {
    vy = -vy;
    vx = int(map( px - mouseX, -35, 35, -8, 8 ));
  }  
  
  // calculate new postion
  px += vx;
  py += vy;
}

void mousePressed() {
  paused = !paused;
  if (done) {
    for( int x = 0; x < 7; x++) {
      for( int y = 0; y < 4; y++ ) {
        stones[x][y] = y + 1;
      }
    }
    done = false;
    px = width/2;
    py = height/2;
    vx = int(random( -8, 8 ));
    vy = -2;
  }

}

